package com.wisdom.util;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.wisdom.bean.VersionBean;
import com.wisdom.tools.HttpUtil;
import com.wisdom.view.HomeSettingActivity;
import com.wisdom.view.HomeTabHostActivity;

public class UpdateManager {
    
    private static UpdateManager mInstance = new UpdateManager();

    private static final String TAG           = "UpdateManager";

    private static final String getVersionUrl = "http://www.1000call.com/api/client/androidupdate";

    private int getVerCode( Context context ) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo("com.bluecall.sipua", 0).versionCode;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verCode;

    }
    
    public static UpdateManager getInstance(){
        return mInstance;
    }

    public void checkUpdate( Context context ) {
        new UpdateTask(context).execute();

    }

    private class UpdateTask extends AsyncTask<Void, Void, VersionBean> {

        private Context context;

        public UpdateTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected VersionBean doInBackground( Void... params ) {
            StringBuilder sb = new StringBuilder();
            sb.append("{\"vercode\":\"");
            sb.append(getVerCode(context));
            sb.append("\"}");
            JSONObject object;
            VersionBean version = null;
            try {
                object = new JSONObject(sb.toString());
                String data = HttpUtil.postReturnStr(getVersionUrl, object);
                System.out.println("data--->" + data.toString());
                version = new Gson().fromJson(data, VersionBean.class);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return version;
        }

        @Override
        protected void onPostExecute( VersionBean result ) {
            if (result != null) {
                if (result.isMustUpdate()) {
                    mustUpdateDialog(context,result);
                }else if(result.isNeedUpdate()){
                    showNeedUpdateDialog(context,result);
                }
            }
            super.onPostExecute(result);
        }

    }

    private void mustUpdateDialog( final Context context, final VersionBean versionBean ) {
        StringBuffer sb = new StringBuffer();
        sb.append("当前版本号:");
        sb.append(getVerCode(context));
        sb.append(", 发现新版本:");
        sb.append(versionBean.getLatestversion());
        sb.append(",新增功能:");
        sb.append(versionBean.getMessage());
        sb.append(", 是否更新?");
        Dialog dialog = new AlertDialog.Builder(context).setTitle("软件更新")
                .setMessage(sb.toString())// 设置内容
                .setPositiveButton("更新",// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick( DialogInterface dialog, int which ) {
                                Intent i = new Intent(Intent.ACTION_VIEW);
                                i.setData(Uri.parse(versionBean.getUrl()));
                                context.startActivity(i);
                                new HomeSettingActivity.LogoutAsyncTask(context).execute();
                                ((HomeTabHostActivity)context).finish();
                            }
                        })
                .setNegativeButton("不更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick( DialogInterface dialog, int which ) {
                        new HomeSettingActivity.LogoutAsyncTask(context).execute();
                        ((HomeTabHostActivity)context).finish();
                    }
                })
                .setCancelable(false)
                .create();// 创建
        // 显示对话框
        dialog.show();
    }

    private void showNeedUpdateDialog( final Context context, final VersionBean versionBean ) {
        StringBuffer sb = new StringBuffer();
        sb.append("当前版本号:");
        sb.append(getVerCode(context));
        sb.append(", 发现新版本:");
        sb.append(versionBean.getLatestversion());
        sb.append(",新增功能:");
        sb.append(versionBean.getMessage());
        sb.append(", 是否更新?");
        Dialog dialog = new AlertDialog.Builder(context).setTitle("软件更新").setMessage(sb.toString())
        // 设置内容
                .setPositiveButton("更新",// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick( DialogInterface dialog, int which ) {
                                Intent i = new Intent(Intent.ACTION_VIEW);
                                i.setData(Uri.parse(versionBean.getUrl()));
                                context.startActivity(i);
                            }
                        }).setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
                    public void onClick( DialogInterface dialog, int whichButton ) {
                        // 点击"取消"按钮之后退出程序
                    }
                }).create();// 创建
        // 显示对话框
        dialog.show();
    }

    private String getVerName( Context context ) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo("com.bluecall.sipua", 0).versionName;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verName;
    }

    public Handler handler = new Handler();

}